package com.tiancan.design.gateway.fillter;

import com.tiancan.design.gateway.bean.RequestCount;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/** @author tiancan */
@Component
@RefreshScope
public class IpLimitGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {
  @Value("${ipLimit.minutes}")
  private Integer minutes;

  @Value("${ipLimit.times}")
  private Integer times;

  private static final Map<String, CopyOnWriteArrayList<RequestCount>> REQUEST_MAP =
      new ConcurrentHashMap<>(256);

  @Override
  public GatewayFilter apply(Object config) {
    return new IpLimitFilter();
  }

  class IpLimitFilter implements GatewayFilter, Ordered, Runnable {

    public IpLimitFilter() {
      Executors.newSingleThreadScheduledExecutor()
          .scheduleWithFixedDelay(this, 0, 5, TimeUnit.SECONDS);
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
      System.out.println("======>>>>>ip防爆刷");
      ServerHttpRequest request = exchange.getRequest();
      String clientId = Objects.requireNonNull(request.getRemoteAddress()).getHostName();
      CopyOnWriteArrayList<RequestCount> requestCountList = REQUEST_MAP.get(clientId);
      System.out.println(times);
      if (requestCountList != null && requestCountList.size() > times) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.SEE_OTHER);
        DataBuffer wrap = response.bufferFactory().wrap(("您频繁进⾏行行注册，请求已被拒").getBytes());
        return response.writeWith(Mono.just(wrap));
      }
      if (requestCountList == null) {
        requestCountList = new CopyOnWriteArrayList<>();
        REQUEST_MAP.put(clientId, requestCountList);
      }
      requestCountList.add(new RequestCount(request.getPath(), System.currentTimeMillis()));
      return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
      return 0;
    }

    @Override
    public void run() {
      REQUEST_MAP.forEach(
          (client, requestCountList) -> {
            requestCountList.removeIf(
                it -> (it.getRequestTime() + minutes * 60 * 1000) < System.currentTimeMillis());
          });
    }
  }
}
